package socket.tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * TCP 客户端
 */
public class TCPClient {
    //建立连接
    public Socket socket = null;

    public TCPClient(String serverIp, int serverPort) throws IOException {
        //如果服务端没有启动, 连接是建立不成功的
        socket = new Socket(serverIp,serverPort);//和服务端建立连接
    }

    public void start(){
        System.out.println("和服务端建立连接....");
        try(OutputStream outputStream = socket.getOutputStream()) {
            PrintWriter writer = new PrintWriter(outputStream);
            //发送数据
            Scanner scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输入发送的数据:");
                String request = scanner.nextLine();//从控制台输入发送的数据
                writer.println(request);
                writer.flush();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPClient client = new TCPClient("127.0.0.1",9090);
        client.start();
    }
}
